<?php

namespace app\admin\controller\news;

use app\common\controller\Backend;
use think\Config;
use fast\Random;
use think\Image;

/**
 * 新闻管理
 *
 * @icon fa fa-circle-o
 */
class News extends Backend
{

    /**
     * News模型对象
     * @var \app\common\model\News
     */
    protected $model = null;
    protected $searchFields = 'id,title,skey,admin.nickname';
    protected $multiFields = 'hot,flag,attribute';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\News;
        $this->view->assign("lxList", $this->model->getLxList());
        $this->view->assign("hotList", $this->model->getHotList());
        $this->view->assign("titleboldList", $this->model->getTitleboldList());
        $this->view->assign("titlecolorList", $this->model->getTitlecolorList());
        $this->view->assign("attributeList", $this->model->getAttributeList());
        $this->view->assign("flagList", $this->model->getFlagList());
        $this->view->assign("qyList", $this->model->getQyList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $groupId = $this->auth->getGroupIds();
            if ($groupId[0] == 7) {
                $map['admin_id'] = $this->auth->id;
            } else {
                $map = [];
            }

            $total = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->where($map)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->where($map)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','image','title','lx', 'hot','updatetime','flag','attribute']);
                $row->visible(['admin']);
				$row->getRelation('admin')->visible(['nickname']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $params['updatetime'] = strtotime("-0 year -6 month -0 day");
                    $result = $this->model->allowField(true)->save($params);

                    // 绑定图片到新闻id
                    $_POST = array();
                    $_POST['news_id'] = $this->model->getLastInsID();
                    $_POST['admin_id'] = $this->auth->id;
                    $newsImage = model('NewsAttachment');
                    if ($params['content']) {
                        $pattern = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg|\.bmp]))[\'|\"].*?[\/]?>/";
                        preg_match_all($pattern, $params['content'],$match);
                        $arr = $match[1];
                        if ($arr) {
                            foreach ($arr as $k => $v) {
                                $v = str_replace(\think\Config::get('upload.cdnurl'),'', $v);
                                if (strlen($v) > 0) {
                                    $newsImage->where('url', $v)->update($_POST);
                                }
                            }
                        }
                    }
                    if ($params['image']) {
                        $_POST['is_cover'] = 1;
                        $newsImage->where('url', $params['image'])->update($_POST);
                    }

                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row) $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $params['updatetime'] = strtotime($params['updatetime']);
                    $result = $row->allowField(true)->save($params);

                    // 绑定图片到新闻id
                    $_POST = array();
                    $_POST['news_id'] = $row->id;
                    $_POST['admin_id'] = $this->auth->id;
                    $newsImage = model('NewsAttachment');
                    if ($params['content']) {
                        $pattern = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg|\.bmp]))[\'|\"].*?[\/]?>/";
                        preg_match_all($pattern, $params['content'],$match);
                        $arr = $match[1];
                        if ($arr) {
                            // 重设新闻图片
                            $newsImage->where('news_id', $_POST['news_id'])->where('is_cover',0)->update(['news_id' => 0]);
                            foreach ($arr as $k => $v) {
                                $v = str_replace(\think\Config::get('upload.cdnurl'),'', $v);
                                if (strlen($v) > 0) {
                                    $newsImage->where('url', $v)->update($_POST);
                                }
                            }
                        }
                    }
                    if ($params['image']) {
                        $_POST['is_cover'] = 1;
                        $newsImage->where('url', $params['image'])->update($_POST);
                    }

                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                // 删除新闻图片
                $arr = model("NewsAttachment")->where('news_id', $v['id'])->select();
                if ($arr) {
                    foreach ($arr as $kk => $vv) {
                        model("NewsAttachment")->where('id', $vv['id'])->delete();
                        $attachmentFile = ROOT_PATH . '/public/uploads' . $vv['url'];
                        if (is_file($attachmentFile))
                        {
                            @unlink($attachmentFile);
                        }
                        //同步删除oss
                        $ftpcfg = get_addon_config('ftp');
                        if ($ftpcfg['ftp_usernmae'] && $ftpcfg['ftp_password']) {
                            $FTP = new \addons\ftp\library\Auth($ftpcfg['ftp_host'], $ftpcfg['ftp_port'], $ftpcfg['ftp_usernmae'], $ftpcfg['ftp_password'], $ftpcfg['ftp_ssh'], $ftpcfg['ftp_pasv']);
                            $FTP->del_file(str_replace('/', DIRECTORY_SEPARATOR, $vv['url']));
                            $FTP->close();
                        }
                    }
                }

                $count += $v->delete();
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 删除新闻封面
     */
    public function delCover()
    {
        if ($this->request->isPost()) {
            $newsid = $this->request->post("newsid");
            $path = $this->request->post("path");
            if ($newsid) {
                $this->model->save(['image' => ''], ['id' => $newsid]);
            }
            model("NewsAttachment")->where('url', 'eq', $path)->delete();
            $attachmentFile = ROOT_PATH . '/public/uploads' . $path;
            if (is_file($attachmentFile))
            {
                @unlink($attachmentFile);
            }
            //同步删除oss
            $ftpcfg = get_addon_config('ftp');
            if ($ftpcfg['ftp_usernmae'] && $ftpcfg['ftp_password']) {
                $FTP = new \addons\ftp\library\Auth($ftpcfg['ftp_host'], $ftpcfg['ftp_port'], $ftpcfg['ftp_usernmae'], $ftpcfg['ftp_password'], $ftpcfg['ftp_ssh'], $ftpcfg['ftp_pasv']);
                $FTP->del_file(str_replace('/', DIRECTORY_SEPARATOR, $path));
                $FTP->close();
            }
            $this->success();
        }
    }
}
